package nl.weeaboo.sh.model;

import timon.common.xml.XmlElement;

public class TileSetModel {

	private String id;
	private TileModel tiles[][];
	
	public TileSetModel(String id, int w, int h) {
		this.id = id;
		
		tiles = new TileModel[w][h];
	}
	
	//Functions
	
	//Getters
	public int getWidth() { return tiles.length; }
	public int getHeight() { return (tiles.length > 0 ? tiles[0].length : 0); }
	
	public TileModel getTileModel(int x, int y) {
		if (x >= 0 && x < tiles.length && y >= 0 && y < tiles[x].length) {
			if (tiles[x][y] == null) {
				tiles[x][y] = new TileModel();
				tiles[x][y].setIndex(new TileSetIndex(this, x, y));
			}
			return tiles[x][y];
		}
		return null;
	}

	public String getId() {
		return id;
	}

	//Setters
	public TileModel putTile(TileModel model) {
		TileSetIndex index = model.getIndex();
		TileModel oldValue = tiles[index.getX()][index.getY()];
		tiles[index.getX()][index.getY()] = model;
		return oldValue;
	}
	
	//Save Support
	public void save(XmlElement parentE) {
		XmlElement e = parentE.addChild("tileSet");
		e.addAttribute("id", getId());
		e.addAttribute("w", getWidth());
		e.addAttribute("h", getHeight());
		
		for (int x = 0; x < tiles.length; x++) {
			for (int y = 0; y < tiles[x].length; y++) {
				if (tiles[x][y] != null) tiles[x][y].save(e);
			}		
		}
	}
	
}
